package cc.cc4414.spring.web.util;

import cc.cc4414.spring.common.result.ResultException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import lombok.experimental.UtilityClass;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * web工具
 *
 * @author cc 2021年03月17日
 */
@UtilityClass
public class WebUtils {
    /**
     * 导出Excel
     *
     * @param data     数据
     * @param response HttpServletResponse对象
     * @param name     文件名称，不带后缀
     * @param isXlsx   是否为xlsx格式
     */
    public void export(Iterable<?> data, HttpServletResponse response, String name, boolean isXlsx) {
        // 获取输出流
        OutputStream out;
        try {
            out = response.getOutputStream();
        } catch (IOException e) {
            throw new ResultException("获取输出流失败！");
        }
        // 设置响应头
        name = URLUtil.encodeAll(name);
        if (isXlsx) {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition", String.format("attachment;filename=%s.xlsx", name));
        } else {
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", String.format("attachment;filename=%s.xls", name));
        }
        // 写入数据
        ExcelWriter writer = ExcelUtil.getWriter(isXlsx);
        writer.write(data);
        writer.flush(out);
        writer.close();
        IoUtil.close(out);
    }

    /**
     * 导出xls格式的Excel
     *
     * @param data     数据
     * @param response HttpServletResponse对象
     * @param name     文件名称，不带后缀
     */
    public void exportXls(Iterable<?> data, HttpServletResponse response, String name) {
        export(data, response, name, false);
    }

    /**
     * 导出xlsx格式的Excel
     *
     * @param data     数据
     * @param response HttpServletResponse对象
     * @param name     文件名称，不带后缀
     */
    public void exportXlsx(Iterable<?> data, HttpServletResponse response, String name) {
        export(data, response, name, true);
    }
}
